package com.itheima.search.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.article.feign.ApArticleFeign;
import com.itheima.article.pojo.ApArticle;
import com.itheima.common.pojo.Result;
import com.itheima.search.dao.ArticleDao;
import com.itheima.search.document.ArticleInfoDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author：shenkunlin
 * @date： 2021/9/2 11:22
 * @Description：
 ***/
@RestController
@RequestMapping(value = "/load")
public class InitLoadArticleController {


    /***
     * 初始化数据导入
     *  1)SpringDataElasticSearch
     *      A:Dao->ElasticsearchRepository<T,T>
     *      B:ElasticsearchRepository->已经具备很多增删改查方法
     *  2)操作ElasticSearch->elasticsearch
     *  3)查询->关键词搜索
     *      A:搜索->封装搜索条件对象XxxQuery,封装搜索条件
     *      B:配置高亮域->指定高亮域、指定高亮的前缀、后缀
     *      C:分页搜索
     *      D:解析结果集
     *           1:非高亮数据
     *           2:高亮数据
     *           3:将非高亮数据替换成高亮数据
     */


    @Autowired
    private ApArticleFeign apArticleFeign;

    @Autowired
    private ArticleDao articleDao;

    /***
     * 批量导入数据
     */
    @GetMapping(value = "/init")
    public Result init(){
        //1)Dao
        //2)从article库中分页查询article数据
        Result<List<ApArticle>> articleResult = apArticleFeign.findAll();
        List<ApArticle> articles = articleResult.getData();

        if(articles!=null && articles.size()>0){
            //3)用Dao将数据批量导入到ElasticSearch
            List<ArticleInfoDocument> docs = JSON.parseArray(JSON.toJSONString(articles), ArticleInfoDocument.class);
            articleDao.saveAll(docs);
        }
        return Result.ok();
    }

}
